<template>
  <div>
    <ay-aside :page-info="pageInfo" />
    <div class="app-container">
      <div class="filter-container">
        <el-button v-waves class="filter-item refresh-btn" icon="el-icon-refresh" @click="handleRefresh" />
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" :disabled="disabledDelBtn" @click="handleDelete(delIdArr)">
          删除
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        fit
        highlight-current-row
        style="width: 100%;"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="30"
          :selectable="selectInit"
        />
        <el-table-column label="#" align="center" width="80">
          <template slot-scope="{$index}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="父级id" align="center" width="200">
          <template slot-scope="{row}">
              <span>{{ row.pid }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="角色名称" min-width="80px">
          <template slot-scope="{row}">
            <span>{{ row.roleName }}</span>
          </template>
        </el-table-column>
  
        <!-- <el-table-column label="状态" align="center" class-name="status-col" width="200">
          <template slot-scope="{row}">
            <el-tag :type="row.status == 1? 'success': 'info'">
              {{ row.status == 1? '正常': '冻结' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="handleUpdate(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete([row.roleId])" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pageTotal > 0" :total="pageTotal" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList" />
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="add-edit-dialog" @close="closeDialog">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="角色名称：" prop="roleName">
            <el-input v-model="temp.roleName" placeholder="输入角色名称" />
          </el-form-item>
          <el-form-item label="菜单权限：" prop="menuIdList">
            <el-tree
              ref="tree"
              :props="props"
              :data="menuTreeData"
              :default-checked-keys="temp.menuIdList"
              show-checkbox
              node-key="menuId"
              style="margin-top: 8px;"
              @check="handleCheck"
            />
          </el-form-item>
      <!--    <el-form-item label="备注：">
            <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="角色备注" />
          </el-form-item> -->
          <!-- <el-form-item label="状态：" prop="status">
            <template>
              <el-radio v-model="temp.status" :label="1">正常</el-radio>
              <el-radio v-model="temp.status" :label="0">冻结</el-radio>
            </template>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus ==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogDelVisible"
        width="30%"
      >
        <span>确定删除数据？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDelVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleList, saveRoleInfo, updateRoleInfo, deletRoleInfo, selectMenuList } from '@/api/privilege'
import { deepClone } from '@/utils/index'
import waves from '@/directive/waves' // waves directive
import AyAside from '@/components/Aside'
import Pagination from '@/components/Pagination'
export default {
  name: 'RoleGroup',
  components: { AyAside, Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      halfCheckedKeys: [],
      isClearable: true, // 下拉树可清空（可选）
      isAccordion: true, // 下拉树可收起（可选）
      props: { // 下拉树配置项（必选）
        value: 'menuId',
        label: 'name',
        children: 'children',
        disabled: true
      },
      radio: '1',
      disabledDelBtn: true,
      dialogIconVisible: false,
      dialogDelVisible: false,
      pageInfo: {},
      list: null,
      listLoading: true,
      selectList: null,
      delIdArr: [],
      temp: {
        roleId: undefined,
        roleName: '',
        menuIdList: [],
        remark: ''
      },
      tableData: [],
      toggleSwitch: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'change' }]
      },
      roleName: '',
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0
    }
  },
  computed: {
    menuTreeData() {
      if (this.selectList) {
        const cloneData = deepClone(this.selectList) // 对源数据深度克隆
        return cloneData.filter(father => {
          const branchArr = cloneData.filter(child => father.menuId === child.parentId) // 返回每一项的子级数组
          branchArr.length > 0 ? father.children = branchArr : father.children = [] // 给父级添加一个children属性，并赋值
          return father.parentId == null // 返回第一层
        })
      }
      return []
    }
  },
  created() {
    this.getList()
    this.pageInfo = this.$route.meta
  },
  methods: {
    // 回显选中的树形菜单
    checkedMenuTree(id, data, checkedArr) {
      data.forEach(item => {
        if (item.menuId === id) {
          if (item.children.length === 0) {
            checkedArr.push(item.menuId)
          }
        } else {
          if (item.children.length !== 0) {
            this.checkedMenuTree(id, item.children, checkedArr)
          }
        }
      })
    },
    // 关闭弹窗时
    closeDialog() {
      this.$nextTick(() => {
        for (let i = 0; i < this.$refs['tree'].store._getAllNodes().length; i++) {
          if (i === 0) {
            this.$refs['tree'].store._getAllNodes()[i].expanded = true
          } else {
            this.$refs['tree'].store._getAllNodes()[i].expanded = false
          }
        }
        this.$refs['tree'].setCheckedKeys([])
      })
    },
    // 菜单树复选框被选择时触发
    handleCheck(data, ck) {
      const tmp = []
      this.halfCheckedKeys = []
      this.halfCheckedKeys.push(...ck.halfCheckedKeys)
      tmp.push(...ck.checkedKeys)
      this.temp.menuIdList = deepClone(tmp)
    },
    // 表格列样式
    tableRowClassName({ row, rowIndex }) {
      if (Number(row.isMenu) === 0) {
        return 'gray-row'
      }
      return ''
    },
    // 禁用选择框
    selectInit(row, index) {
      if (Number(row.isMenu) === 0) {
        return false
      } else {
        return true
      }
    },
    // 获取表格数据接口
    getList() {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        getRoleList({
          roleName: this.roleName,
          createUserId: null,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }).then(response => {
          this.list = response.data.list
          this.pageTotal = response.data.total
          this.pageSize = response.data.pageSize
          this.pageNum = response.data.pageNum
          const cloneData = deepClone(this.list)
          selectMenuList().then((response) => {
            this.selectList = response.data.menuList
            const zeroNode = {
              icon: '',
              list: null,
              menuId: '0',
              name: '全部菜单',
              open: null,
              orderNum: 0,
              parentId: null,
              parentName: null,
              perms: null,
              type: 0,
              url: ''
            }
            this.selectList.push(zeroNode)
          })
          this.tableData = cloneData
          this.listLoading = false
          resolve(true)
        }).catch(error => {
          console.log(error)
          this.$message({
            message: error,
            type: 'error'
          })
          reject(false)
        })
      }
      )
    },
    // 刷新
    async handleRefresh() {
      if (await this.getList()) {
        this.$message({
          message: '刷新成功',
          type: 'success'
        })
      }
    },
    // 新增操作
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // this.$refs['tree'].setCheckedKeys([]);
        this.$refs['tree'].store._getAllNodes()[0].expanded = true
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 表格选中时触发
    handleSelectionChange(selection) {
      this.delIdArr = []
      if (selection.length) {
        this.disabledDelBtn = false
        for (const i in selection) {
          this.delIdArr.push(selection[i].roleId)
        }
      } else {
        this.disabledDelBtn = true
      }
      console.log(this.delIdArr)
    },
    // 初始化表单
    resetTemp() {
      this.temp = {
        roleId: undefined,
        roleName: '',
        menuIdList: [],
        remark: ''
      }
    },
    // 新增数据接口
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.menuIdList.push(...this.halfCheckedKeys)
          saveRoleInfo(this.temp).then((response) => {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 编辑操作
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      var checkedArr = []
      this.temp.menuIdList.forEach((id) => {
        this.checkedMenuTree(id, this.menuTreeData, checkedArr)
      })
      this.temp.menuIdList = checkedArr
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据接口
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.menuIdList.push(...this.halfCheckedKeys)
          updateRoleInfo(this.temp).then((response) => {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 删除操作
    handleDelete(idArr) {
      this.dialogDelVisible = true
      this.delIdArr = idArr
    },
    deleteData() {
      deletRoleInfo(this.delIdArr).then(() => {
        this.dialogDelVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .el-table {
    .gray-row {
      color: #c2d2d2;
    }
  }
  .add-edit-dialog {
    .el-dialog{
      .el-dialog__body{
        height: 480px;
        overflow: auto;
      }
    }
  }
  .el-button--mini{
    padding: 7px;
  }
  .filter-container{
    .filter-item {
      margin-left: 0;
      &.refresh-btn{
        background-color: #030303;
        color: azure;
      }
    }
  }
}
</style>
